<template>
  <div class="permission">
    <el-card class="top">
      <el-button type="primary" @click="addEvent">添加权限</el-button>
    </el-card>
    <el-table
      :data="list"
      row-key="id"
      border
      :header-cell-style="{ textAlign: 'center' }"
      :cell-style="{ textAlign: 'center' }"
    >
      <el-table-column prop="name" label="名称" />
      <el-table-column prop="code" label="标识" />
      <el-table-column prop="description" label="描述" />
      <el-table-column label="操作">
        <template v-slot="{ row }">
          <el-button type="text" @click="addEvent2(row.id)">添加</el-button>
          <el-button type="text" @click="editEvent(row)">编辑</el-button>
          <el-button type="text" @click="delEvent(row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <Add ref="add" @getData="getData" />
  </div>
</template>

<script>
import { sysPermisson, sysPermissionDelete } from '@/api/permission'
import Add from './components/Add.vue'
export default {
  components: { Add },
  data() {
    return {
      list: []
    }
  },
  created() {
    this.getData()
  },
  methods: {
    async getData() {
      const res = await sysPermisson()
      this.list = this.changeData(res.data, '0')
    },
    changeData(arr, pid) {
      return arr.filter((item) => {
        if (item.pid === pid) {
          item.children = this.changeData(arr, item.id)
          return true
        }
      })
    },
    // 新增页面权限
    addEvent() {
      this.$refs.add.show = true
      this.$refs.add.form.type = 1
      this.$refs.add.form.pid = '0'
      this.$refs.add.mode = 'add'
    },
    // 新增子权限
    addEvent2(id) {
      this.$refs.add.show = true
      this.$refs.add.form.type = 2
      this.$refs.add.form.pid = id
      this.$refs.add.mode = 'add'
    },
    // 编辑权限
    editEvent(row) {
      this.$refs.add.show = true
      // 数据回显（深拷贝）
      this.$refs.add.form = JSON.parse(JSON.stringify(row))
      this.$refs.add.mode = 'edit'
    },
    // 删除权限
    async delEvent(id) {
      await this.$confirm('您确定删除该权限点吗？', '温馨提示')
      await sysPermissionDelete(id)
      this.$message.success('删除成功')
      this.getData()
    }
  }
}
</script>

<style lang="scss" scoped>
.permission {
  padding: 30px;
  .top {
    text-align: right;
    margin-bottom: 20px;
  }
}
</style>
